package com.itheima.service;


import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService implements UserDetailsService {
//    如果想要用数据库中的数据而不是在xml中的数据必须实现UserDetailService并实现方法
//    这个方法不需要自己调用而是由Spring容器调用]
    private static Map map ;
    static {
//        模拟数据库 从数据库中添加几个用户
         map =new HashMap<>();
        User user1 = new User( ) ;
        user1.setUsername("user1");
        user1.setPassword("pass1");
        User user2 = new User();
        user2.setUsername("admin");
        user2.setPassword("admin");
        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);

}
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户输入的用户名为:"+username);
//        跟上用户名查询数据库获得用户信息（包含数据库中存储的密码信息） 注意这里不用mybatis而是用SpringSecurity进行查询
        User user = (User) map.get(username);
        if (user==null){
            return null;
        }else {
            //            用户名存在
            //        框架会进行密码比对
            List<GrantedAuthority> list = new ArrayList();
            list.add(new SimpleGrantedAuthority("permission_A"));
            list.add(new SimpleGrantedAuthority("permission_B"));

            if (username.equals("admin")) {
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            org.springframework.security.core.userdetails.User userSpring = new org.springframework.security.core.userdetails.User(username,"{noop}"+user.getPassword(),list);
            return userSpring;
        }




    }
}
